import { Cross2Icon } from '@radix-ui/react-icons'
import { type Table } from '@tanstack/react-table'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { DataTableFacetedFilter } from './data-table-faceted-filter'
import { DataTableViewOptions } from './data-table-view-options'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { IconAlertTriangle } from '@tabler/icons-react'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { IconTrash } from '@tabler/icons-react'

import { useState } from 'react'
import { toast } from 'sonner'
import { convertTreeSelectedToString } from '@/utils/tree-util'
import { useAdminDelete } from '@/api/admins'
import { useRouter } from '@tanstack/react-router'

interface DataTableToolbarProps<TData> {
  table: Table<TData>
}

export function DataTableToolbar<TData>({
  table,
}: DataTableToolbarProps<TData>) {
  const isFiltered = table.getState().columnFilters.length > 0
  const isSelected = table.getFilteredSelectedRowModel().rows.length > 0
  const selectedItems = convertTreeSelectedToString(table.getState().rowSelection)
  const router = useRouter()
  const [open, setOpen] = useState(false)
  const adminDelete = useAdminDelete()
  const handleDelete = () => {
    adminDelete.mutate({ id: selectedItems.split(',') }, {
      onSuccess: () => {
        setOpen(false)
        toast.success('Deleted successfully!')
        router.invalidate();
      },
    })
  }
  const onOpenChange = () => {
    setOpen(!open)
  }
  return (
    <div className='flex items-center justify-between'>
      <div className='flex flex-1 flex-col-reverse items-start gap-y-2 sm:flex-row sm:items-center sm:space-x-2'>
        <Input
          placeholder='Filter username...'
          value={
            (table.getColumn('username')?.getFilterValue() as string) ?? ''
          }
          onChange={(event) =>
            table.getColumn('username')?.setFilterValue(event.target.value)
          }
          className='h-8 w-[150px] lg:w-[250px]'
        />
        <div className='flex gap-x-2'>
          {table.getColumn('status_cn') && (
            <DataTableFacetedFilter
              column={table.getColumn('status_cn')}
              title='Status'
              options={[
                { label: 'Normal', value: 'normal' },
                { label: 'Disabled', value: 'disabled' },
              ]}
            />
          )}
        </div>
        {isFiltered && (
          <Button
            variant='ghost'
            onClick={() => table.resetColumnFilters()}
            className='h-8 px-2 lg:px-3'
          >
            Reset
            <Cross2Icon className='ml-2 h-4 w-4' />
          </Button>
        )}
        {
          isSelected && (
            <>
              <Button
                variant='outline'
                onClick={() => setOpen(true)}
                className='h-8 px-2 lg:px-3 text-red-500!'
              >
                Delete
                <IconTrash size={16} />
              </Button>
              <ConfirmDialog
                open={open}
                onOpenChange={onOpenChange}
                handleConfirm={handleDelete}
                title={
                  <span className='text-destructive'>
                    <IconAlertTriangle
                      className='stroke-destructive mr-1 inline-block'
                      size={18}
                    />{' '}
                    Delete User
                  </span>
                }
                desc={
                  <div className='space-y-4'>
                    <p className='mb-2'>
                      Are you sure you want to delete{selectedItems}
                      <span className='font-bold'>{ }</span>?
                      <br />

                      from the system. This cannot be undone.
                    </p>

                    <Alert variant='destructive'>
                      <AlertTitle>Warning!</AlertTitle>
                      <AlertDescription>
                        Please be carefull, this operation can not be rolled back.
                      </AlertDescription>
                    </Alert>
                  </div>
                }
                confirmText='Delete'
                destructive
              />
            </>
          )
        }
      </div>
      <DataTableViewOptions table={table} />
    </div>
  )
}
